<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <ul>
        <li><a href="#/home">首页</a></li>
        <li><a href="#/about">关于</a></li>
    </ul>
    <!--  当url变更后，展示对应的代码片段 -->
    <div class="root">
    </div>
    <script>
        const routes = [
            {
                path: '/home',
                component: () => {
                    return '<h1>首页</h1>'
                }
            },
            {
                path: '/about',
                component: () => {
                    return '<h1>关于</h1>'
                }
            }
        ]
        // 当url变更后，展示对应的代码片段
        window.addEventListener('hashchange', function () {
            console.log(location.hash);
            // 1. 获取hash值
            const hash = location.hash;
            // 2. 调用RenderPage函数
            RenderPage(hash);
        })

        function RenderPage(url) {
            // 1. 去掉#
            const hashWithoutHash = url.replace('#', '');
            // 2. 遍历路由表
            for (const route of routes) {
                if (route.path === hashWithoutHash) {
                    // 4. 找到匹配的路由，调用组件函数
                    const component = route.component();
                    // 5. 展示组件
                    document.querySelector('.root').innerHTML = component;
                }
            }
        }

        window.addEventListener("DOMContentLoaded", function () {
            // 1. 获取hash值
            const hash = location.hash;
            // 2. 调用RenderPage函数
            RenderPage(hash);
        })
    </script>
</body>

</html>